package com.mresources.web.service;

import com.mresources.common.auth.EndPoint;
import com.mresources.common.auth.Oauth2Config;
import com.mresources.common.dto.Token;
import com.mresources.common.utils.JsonUtil;
import com.mresources.common.utils.WebUtil;
import lombok.SneakyThrows;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Service
public class Oauth2Service {
    private static final Base64.Encoder encoder = Base64.getEncoder();

    public Oauth2Config getConfig() {
        return Oauth2Config.builder()
                .clientID("22222")
                .clientSecret("$2a$10$ZRmPFVgE6o2aoaK6hv49pOt5BZIKBDLywCaFkuAs6zYmRkpKHgyuO")
                .redirectURL("http://localhost:8888/oauth2/callback")
                .authServerURL("http://localhost:8889")
                .scopes(Collections.singletonList("all"))
                .state("xyz")
                .endPoint(
                        EndPoint.builder()
                                .authURL("/oauth2/authorize")
                                .tokenURL("/oauth2/token").build()
                ).build();
    }

    @SneakyThrows
    public Token getToken(Oauth2Config config, String code, String state) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        String authString = (config.getClientID() + ":" + config.getClientSecret());
        String encode = encoder.encodeToString(authString.getBytes(StandardCharsets.UTF_8));
        headers.put("Authorization", "Basic " + encode);

        String tokenUrl = config.fetchOauth2TokenUrl(code, state);
        HttpResponse back = WebUtil.visitWithResponse(tokenUrl, WebUtil.POST, headers);
        return JsonUtil.stringToObject(EntityUtils.toString(back.getEntity()), Token.class);
    }
}
